package com.ndp.fb.mq.service.schedulerservice.thirdpictureaudit;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.enums.adgroupstatus.AdGroupStatus;
import com.ndp.fb.enums.adresource.ThirdPicReviewStatus;
import com.ndp.fb.fbagent.service.AdGroupFBService;
import com.ndp.fb.mongo.api.AdResourceStatsMongoService;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.rdb.api.ThirdPicAutoAuditRdbService;
import com.ndp.fb.rdb.model.ThirdPicAutoAudit;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Evan on 2015/10/19.
 */
@Component
public class AdGroupAuditForThirdPicService {
    private static Logger logger = LoggerFactory.getLogger(AdGroupAuditForThirdPicService.class);

    @Autowired
    private AdAccountsSchedulerService adaccountsSchedulerService;

    @Reference
    private ThirdPicAutoAuditRdbService thirdPicAutoAuditRdbService;

    @Reference
    private AdGroupFBService adGroupFBService;

    @Reference
    private AdResourceStatsMongoService adResourceStatsMongoService;

    /**
     * 机器审核广告 定时任务begin
     */
    public void auditAdFix() {
        logger.info("needFix的广告{}", 1);
        List<ThirdPicAutoAudit> noDealList = thirdPicAutoAuditRdbService.findNoDealAd();
        if(ListUtil.isEmpty(noDealList))
            return;
        Long accountId = AutoCheckConstant.getFbAccountId();
        logger.info("needFix的广告{}", 2);
        String accessToken = adaccountsSchedulerService.getAdaccountsToken(accountId);
        if(StringUtil.isEmpty(accessToken))
            return;
        logger.info("needFix的广告{}", 3);
        for(ThirdPicAutoAudit obj : noDealList)
        {
            logger.info("自动查找needFix的广告{}----begin", obj.getAdGroupId());
            adGroupFBService.getOneAdGroupStatus(accessToken, accountId, obj.getAdGroupId(), obj.getMongodbId());
        }
    }

    public void auditAdFixCallback(Map<String, String> equipment, Object callBackObject) {
        logger.info("AdGroupAuditForThirdPicService auditAdFixCallback 获取审核状态回调begin. ");
        JsonObject jsonObject = new JsonObject(callBackObject.toString());
        try{
            if (jsonObject.has(AutoCheckConstant.getAdStatusName()) && jsonObject.has("id")) {
                String mongodbId = equipment.get("mongodbId");
                JSONObject fbObject = JSONObject.parseObject(callBackObject.toString());     //获取的单个广告 对象
                Long adGroupId = Long.parseLong(fbObject.get("id").toString());         //广告id
                String adGroupStatus = fbObject.get(AutoCheckConstant.getAdStatusName()).toString();   //状态
                Object adReviewFeedback = fbObject.get(AutoCheckConstant.getAdReviewFeedbackName()); //广告审核反馈

                if (adGroupStatus.equalsIgnoreCase(AdGroupStatus.PENDING_REVIEW.getStatus())) {
                    logger.info("机器审核ing，adGroupId:{}", adGroupId);
                } else if (adGroupStatus.equalsIgnoreCase(AdGroupStatus.ACTIVE.getStatus())) {
                    logger.info("机器审核pass，更新adresourcestatsbyday，adGroupId:{}", adGroupId);
                    //一、更新adresourcestatsbyday 审核状态
                    adResourceStatsMongoService.updateReviewStatus(mongodbId, ThirdPicReviewStatus.MACHINE_REVIEW_PASS.getCode(), "", 0);
                    //二、更改审核标记 flag=1 已处理 下一次调度不再处理
                    thirdPicAutoAuditRdbService.updateFlagByAdGroupId(adGroupId);
                } else {
                    logger.info("机器审核nopass，更新adresourcestatsbyday，adGroupId:{}", adGroupId);
                    //一、更新adresourcestatsbyday 审核状态
                    adResourceStatsMongoService.updateReviewStatus(mongodbId, ThirdPicReviewStatus.MACHINE_REVIEW_NOPASS.getCode(), adReviewFeedback == null ? "" : adReviewFeedback.toString(), 0);
                    //二、更改审核标记 flag=1 已处理 下一次调度不再处理
                    thirdPicAutoAuditRdbService.updateFlagByAdGroupId(adGroupId);
                }
            }
        } catch (Exception e) {
            logger.error("wanwencheng调查机器审核错误", e);

        }
    }


    public void auditAdCallback(Map<String, String> equipment, Object callBackObject) {
        logger.info("AdGroupAuditForThirdPicService auditAdCallback 获取审核状态回调begin. ");
        JsonObject jsonObject = new JsonObject(callBackObject.toString());
        try{
            if (jsonObject.has("data")) {

                Long adSetId = Long.parseLong(equipment.get("adSetId"));
                //找到该系列下的机器审核图片数据
                List<ThirdPicAutoAudit> auditList = thirdPicAutoAuditRdbService.findByAdSetId(adSetId);
                if(ListUtil.isEmpty(auditList)) {
                    return;
                }
                JsonArray jsonSummary = jsonObject.getJsonArray("data");
                if (jsonSummary.length() == 0) {
                    return;
                } else {
                    Map<Long, String> map = new HashMap<>();
                    for(ThirdPicAutoAudit thirdPicAutoAudit : auditList)
                    {
                        map.put(thirdPicAutoAudit.getAdGroupId(), thirdPicAutoAudit.getMongodbId());
                    }
                    JSONObject fbObject;     //获取的单个广告 对象
                    Long adGroupId;          //广告id
                    String adGroupStatus;    //状态
                    Object adReviewFeedback; //广告审核反馈
                    for (int i = 0; i < jsonSummary.length(); i++) {
                        fbObject = JSONObject.parseObject(jsonSummary.get(i).toString());
                        adGroupId = Long.parseLong(fbObject.get("id").toString());
                        if(StringUtil.isEmpty(map.get(adGroupId)))
                            continue;
                        adGroupStatus = fbObject.get("adgroup_status").toString();
                        adReviewFeedback = fbObject.get("adgroup_review_feedback");
                        if (adGroupStatus.equalsIgnoreCase(AdGroupStatus.PENDING_REVIEW.getStatus())) {
                            logger.info("机器审核ing，adGroupId:{}", adGroupId);
                        } else if (adGroupStatus.equalsIgnoreCase(AdGroupStatus.ACTIVE.getStatus())) {
                            logger.info("机器审核pass，更新adresourcestatsbyday，adGroupId:{}", adGroupId);
                            //一、更新adresourcestatsbyday 审核状态
                            adResourceStatsMongoService.updateReviewStatus(map.get(adGroupId), ThirdPicReviewStatus.MACHINE_REVIEW_PASS.getCode(), "", 0);
                            //二、更改审核标记 flag=1 已处理 下一次调度不再处理
                            thirdPicAutoAuditRdbService.updateFlagByAdGroupId(adGroupId);
                            //final Long orgId = orgIdMap.get(adGroupId);
                            //三、发送图片机器审核通过消息
                        } else {
                            logger.info("机器审核nopass，更新adresourcestatsbyday，adGroupId:{}", adGroupId);
                            //一、更新adresourcestatsbyday 审核状态
                            adResourceStatsMongoService.updateReviewStatus(map.get(adGroupId), ThirdPicReviewStatus.MACHINE_REVIEW_NOPASS.getCode(), adReviewFeedback == null ? "" : adReviewFeedback.toString(), 0);
                            //二、更改审核标记 flag=1 已处理 下一次调度不再处理
                            thirdPicAutoAuditRdbService.updateFlagByAdGroupId(adGroupId);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("wanwencheng调查机器审核错误", e.getMessage());

        }
    }



}
